package com.zhongxi.guoyuan.adapter.shopCart;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.entity.rewardcoin.ShopCartResult;
import com.zhongxi.guoyuan.entity.shopcart.Attr;
import com.zhongxi.guoyuan.entity.shopcart.GoodsInfo;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.widget.sliding.NoScrollListView;

import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Administrator on 2016/11/26.
 */

public class ShoppingCartAdapter extends BaseAdapter implements AdapterView.OnItemClickListener {

    //填充数据的list
    private List<ShopCartResult.ToDoor> list;
    //用来控制CheckBox的选中状态
    private ArrayList<Boolean> isSelected;
    private boolean isAllChecked = false;
    //上下文
    private Context context;
    //用来导入布局
    private LayoutInflater mLayoutInflater;
    private int number = 0;			//记录对话框中的数量

    private int mExpandedMenuPos = -1;

    private JSONObject info;
    private JSONObject attr;
    private JSONObject address;
    private Handler handler;
    private AttrCartAdapter attrAdapter;

    //构造器
    public ShoppingCartAdapter(Context conext, List<ShopCartResult.ToDoor> list, Handler handler){
        this.context = conext;
        this.mLayoutInflater = LayoutInflater.from(conext);
        this.list = list;
        this.handler = handler;
        isSelected = new ArrayList<>();
    }

    public boolean isAllChecked() {
        return isAllChecked;
    }

    public void setAllChecked(boolean allChecked) {
        isAllChecked = allChecked;
    }

    public List<ShopCartResult.ToDoor> getList() {
        return list;
    }

    public void setList(List<ShopCartResult.ToDoor> list) {
        this.list = list;
    }

    public int getmExpandedMenuPos() {
        return mExpandedMenuPos;
    }

    public void setmExpandedMenuPos(int mExpandedMenuPos) {
        this.mExpandedMenuPos = mExpandedMenuPos;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        try {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mLayoutInflater.inflate(R.layout.item_shopping_cart, parent, false);
                holder.ivImg = (ImageView) convertView.findViewById(R.id.ivImg);
                holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
                holder.tvAdd = (TextView) convertView.findViewById(R.id.tvAdd);
                holder.tvSub = (TextView) convertView.findViewById(R.id.tvSub);
                holder.tvPrice = (TextView) convertView.findViewById(R.id.tvMoney);
                holder.etNum = (EditText) convertView.findViewById(R.id.etNum);
                holder.ivCheck = (ImageView) convertView.findViewById(R.id.ivSelect);
                holder.lvList = (NoScrollListView) convertView.findViewById(R.id.lvList);
                holder.linear_item = (LinearLayout) convertView.findViewById(R.id.linear_item);
                holder.tvEdit = (TextView) convertView.findViewById(R.id.tvEdit);
                holder.tvNature = (TextView) convertView.findViewById(R.id.tvNature);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final int p = position;
            final ViewHolder hol = holder;
            ShopCartResult.ToDoor data = list.get(position);
            if(!"".equals(data.getGoodsnum())){
                holder.etNum.setText(data.getGoodsnum()+"");
            }
            if(null!=data.getGattr()&&!"".equals(data.getGattr())){
                JSONObject obj = new JSONObject(data.getGattr());
                Iterator<String> iterator = obj.keys();
                List<String> key = new ArrayList<>();
                List<String> value = new ArrayList<>();
                List<Attr> attrList = new ArrayList<>();
                String str = "";
                while (iterator.hasNext()){
                    String next = iterator.next();
                    key.add(next);
                    value.add(obj.getString(next));
                    str += "/"+obj.getString(next);
                    Attr attr = new Attr(next, obj.getString(next));
                    attrList.add(attr);
                }
                list.get(position).setAttr(attrList);
                holder.tvNature.setText(str);
                if(null!=attr&&!"".equals(attr)){
                    JSONObject attrObj = new JSONObject(attr.getString(data.getGoodsid()));
                    JSONObject a = attrObj.getJSONObject("attr");
                    attrAdapter = new AttrCartAdapter(context, attrObj.getJSONObject("attr"), key, value, list.get(position));
                    holder.lvList.setAdapter(attrAdapter);
                }
            }else{
                holder.tvNature.setText("");
            }
            if(null!=info&&!"".equals(info)){
                if(null!=data.getGoodsid()&&!"".equals(data.getGoodsid())){
                    GoodsInfo goodsInfo = GoodsInfo.parseMatch(info.getJSONObject(data.getGoodsid()));
                    if(null!=goodsInfo&&!"".equals(goodsInfo)){
                        if(null!=goodsInfo.getName()&&!"".equals(goodsInfo.getName())){
                            holder.tvName.setText(goodsInfo.getName());
                        }else{
                            holder.tvName.setText("");
                        }
                        if(null!=goodsInfo.getPrice()&&!"".equals(goodsInfo.getPrice())){
                            BigDecimal bd = new BigDecimal(goodsInfo.getPrice());
                            holder.tvPrice.setText(bd.multiply(new BigDecimal(data.getGoodsnum()))+"元[返"+bd.multiply(new BigDecimal(data.getGoodsnum())).intValue()+"银币]");
                        }else{
                            holder.tvPrice.setText("");
                        }
                        if(null!=goodsInfo.getThumbnail()&&!"".equals(goodsInfo.getThumbnail())){
                            Glide.with(context).load(Url.IMG_URL+goodsInfo.getThumbnail()).fitCenter().placeholder(R.mipmap.iv_eg).into(holder.ivImg);
                        }
                    }
                }
            }

            if (isAllChecked) {
                holder.ivCheck.setImageResource(R.mipmap.yes);
            } else if (data.isChecked()) {
                holder.ivCheck.setImageResource(R.mipmap.yes);
            } else {
                holder.ivCheck.setImageResource(R.mipmap.no);
            }
            holder.ivCheck.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!list.get(p).isChecked()) {
                        hol.ivCheck.setImageResource(R.mipmap.yes);
                        list.get(p).setChecked(true);
                    } else {
                        hol.ivCheck.setImageResource(R.mipmap.no);
                        isAllChecked = false;
                        list.get(p).setChecked(false);
                    }
                }
            });
            //减少
            holder.tvSub.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    number = list.get(p).getGoodsnum();
                    if (number > 1) {
                        number--;
                        list.get(p).setGoodsnum(number);
                        notifyDataSetChanged();
                    }
                }
            });
            //增加
            holder.tvAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    number = list.get(p).getGoodsnum();
                    number++;
                    list.get(p).setGoodsnum(number);
                    notifyDataSetChanged();
                }
            });

            holder.tvEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (p == getmExpandedMenuPos()) {
                        hol.tvEdit.setText("编辑");
                        Message msg = Message.obtain();
                        msg.what = 1;
                        msg.obj = position;
                        handler.sendMessage(msg);
                    } else {
                        setmExpandedMenuPos(p);
                        hol.tvEdit.setText("完成");
                        notifyDataSetChanged();
                    }
                }
            });

            holder.linear_item.setVisibility(position == mExpandedMenuPos ? View.VISIBLE : View.GONE);

        }catch (Exception e){
            e.printStackTrace();
        }

        return convertView;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    public void setGoodsInfo(JSONObject info, JSONObject attr, JSONObject address) {
        this.info = info;
        this.attr = attr;
        this.address = address;
    }

    class ViewHolder{
        private TextView tvName;
        private EditText etNum;
        private TextView tvPrice;
        private TextView tvAdd;
        private TextView tvSub;
        private ImageView ivCheck;
        private NoScrollListView lvList;
        private LinearLayout linear_item;
        private TextView tvEdit;
        private TextView tvNature;
        private ImageView ivImg;
    }

}
